﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using FaWorksSolution.MvcApplication.Models;
using System.IO;

namespace FaWorksSolution.MvcApplication.Hubs
{
    public class FileManageHub : Hub
    {
        //服务端发送文件对象到客户端
        public void SendItem(object o)
        {
            System.Threading.Thread.Sleep(100);
            Clients.All.ReceiveItem(o);
        }

        public void SendOver()
        {
            Clients.All.OnScanOver();
        }

        //全盘扫描
        public void ScanDisks(string path) {
            if (string.IsNullOrEmpty(path))
            {
                foreach (DriveInfo di in DriveInfo.GetDrives())
                {
                    ScanDirctory(di.Name);
                }
            }
            else {
                ScanDirctory(path);
            }

            SendOver();
        }

        public void ScanDirctory(string path) {
            DirectoryInfo dir = new DirectoryInfo(path);

            try {
                foreach (DirectoryInfo di in dir.GetDirectories("*", SearchOption.TopDirectoryOnly))
                {
                    SendItem(new
                    {
                        ParentPath = path,
                        Path = di.FullName,
                        Name = di.Name,
                        Type = "folder"
                    });

                    ScanDirctory(di.FullName);
                }

                foreach (FileInfo fi in dir.GetFiles("*.*", SearchOption.TopDirectoryOnly))
                {
                    SendItem(new
                    {
                        ParentPath = path,
                        Path = fi.FullName,
                        Name = fi.Name,
                        Type = fi.Extension.TrimStart('.')
                    });
                }
            }
            catch (Exception ex)
            {
                SendItem(new
                {
                    Type = "error",
                    Message = ex.Message
                });
            }
        }

        public override System.Threading.Tasks.Task OnDisconnected()
        {
            return base.OnDisconnected();
        }
    }
}